{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# [Reverse Integer（反转整数）](https://mp.weixin.qq.com/s/6mjYd7jMhVC3inzxuKHC5A)\n",
    "\n",
    "[@mjd507](https://mp.weixin.qq.com/s/6mjYd7jMhVC3inzxuKHC5A)\n",
    "\n",
    "![Logo](DP-68.png)\n",
    "\n",
    "Write a function that reverses the digits of a **32-bit signed integer**, $x$. Assume that the environment can only store integers within the 32-bit signed integer range, from $-2^{31}$ to $2^{31}$. The function returns $0$ when the reversed integer overflows.\n",
    "\n",
    "编写一个翻转**32位有符号整数**数位的函数。注意运算环境只能接受32位有符号整数，范围从$-2^{31}$到$2^{31}$。当反转的整数值溢出时，返回$0$。\n",
    "\n",
    "```text\n",
    "In [1]: 123\n",
    "Out [1]: 321\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Solution:\n",
    "    def reverse(self, x: int) -> int:\n",
    "        if bin(x)[0] == '0' and x.bit_length() > 31:\n",
    "            return 0\n",
    "        elif bin(x)[0] == '1' and x.bit_length() > 32:\n",
    "            return 0\n",
    "        else:\n",
    "            if x < 0:\n",
    "                x = abs(x)\n",
    "                string = str(x)\n",
    "                return int('-' + string[-1::-1])\n",
    "            else:\n",
    "                string = str(x)\n",
    "                return int(string[-1::-1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "321"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "solution = Solution()\n",
    "solution.reverse(123)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "solution.reverse(2 ** 31)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
